<template>
    <div class="create-container">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/" class="custom-breadcrumb">
            <el-breadcrumb-item><span class="breadcrumb-strong">登录</span></el-breadcrumb-item>
            <el-breadcrumb-item><span class="breadcrumb-strong">首页</span></el-breadcrumb-item>
            <el-breadcrumb-item>创建应用</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 查询条件卡片 -->
        <el-card class="search-card">
            <el-form :model="formData" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="表单分类:">
                            <el-select v-model="formData.typeId" placeholder="请选择表单分类" style="width: 100%;" clearable
                                @change="handleTypeChange">
                                <el-option v-for="item in formTypeOptions" :key="item.TypeId" :label="item.TypeName"
                                    :value="item.TypeId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="表单:">
                            <el-select v-model="formData.formId" placeholder="请选择表单" style="width: 100%;" clearable
                                @change="handleFormChange">
                                <el-option v-for="item in formOptions" :key="item.FormId" :label="item.FormName"
                                    :value="item.FormId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <!-- 明细卡片 -->
        <el-card class="detail-card">
            <el-form :model="formData" label-width="120px">
                <template v-if="formDetails.length > 0">
                    <el-divider content-position="left">表单明细</el-divider>
                    <el-row :gutter="24" style="margin-bottom: 0; flex-wrap: wrap;">
                        <el-col v-for="(detail, index) in formDetails" :key="index" :span="8"
                            style="margin-bottom: 18px;">
                            <el-form-item :label="detail.FieldDesc">
                                <!-- 根据控件类型动态渲染不同的表单控件 -->
                                <!-- 文本框 -->
                                <el-input v-if="detail.FieldControl === 'text'"
                                    v-model="formData.dynamicFields[detail.FieldName]"
                                    :placeholder="`请输入${detail.FieldDesc}`" />

                                <!-- 下拉框 -->
                                <el-select v-else-if="detail.FieldControl === 'select'"
                                    v-model="formData.dynamicFields[detail.FieldName]"
                                    :placeholder="`请选择${detail.FieldDesc}`" style="width: 100%;" clearable>
                                    <el-option v-for="option in getFieldOptions(detail)" :key="option.value"
                                        :label="option.label" :value="option.value" />
                                </el-select>

                                <!-- 单选框 -->
                                <el-radio-group v-else-if="detail.FieldControl === 'radio'"
                                    v-model="formData.dynamicFields[detail.FieldName]">
                                    <el-radio v-for="option in getFieldOptions(detail)" :key="option.value"
                                        :label="option.value">{{ option.label }}</el-radio>
                                </el-radio-group>

                                <!-- 复选框 -->
                                <el-checkbox-group v-else-if="detail.FieldControl === 'checkbox'"
                                    v-model="formData.dynamicFields[detail.FieldName]">
                                    <el-checkbox v-for="option in getFieldOptions(detail)" :key="option.value"
                                        :label="option.value">{{ option.label }}</el-checkbox>
                                </el-checkbox-group>

                                <!-- 日期选择器 -->
                                <el-date-picker v-else-if="detail.FieldControl === 'date'"
                                    v-model="formData.dynamicFields[detail.FieldName]" type="date"
                                    :placeholder="`请选择${detail.FieldDesc}`" style="width: 100%;" />

                                <!-- 时间选择器 -->
                                <el-date-picker v-else-if="detail.FieldControl === 'datetime'"
                                    v-model="formData.dynamicFields[detail.FieldName]" type="datetime"
                                    :placeholder="`请选择${detail.FieldDesc}`" style="width: 100%;" />

                                <!-- 文本域 -->
                                <el-input v-else-if="detail.FieldControl === 'textarea'"
                                    v-model="formData.dynamicFields[detail.FieldName]" type="textarea" :rows="3"
                                    :placeholder="`请输入${detail.FieldDesc}`" />

                                <!-- 默认文本框 -->
                                <el-input v-else v-model="formData.dynamicFields[detail.FieldName]"
                                    :placeholder="`请输入${detail.FieldDesc}`" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
                <!-- 操作按钮 -->
                <el-form-item v-if="formDetails.length > 0">
                    <el-button type="primary" @click="handleSubmit">提交</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { GetFormTypeList } from '@/api/formType'; // 引入表单类型接口
import { getFormList } from '@/api/formInfo'; // 引入表单接口
import { getfetchFormDetail } from '@/api/formDetail'; // 引入表单明细接口

// 表单数据
const formData = reactive({
    typeId: null as string | null,
    formId: null as number | null,
    dynamicFields: {} as Record<string, any>
});

// 表单类型选项
const formTypeOptions = ref<any[]>([]);
// 表单选项
const formOptions = ref<any[]>([]);
// 表单明细
const formDetails = ref<any[]>([]);

// 获取表单类型列表
const getFormTypeOptions = async () => {
    try {
        const res = await GetFormTypeList();
        if (res && res.data && res.data.Result) {
            formTypeOptions.value = res.data.Result;
        }
    } catch (error) {
        console.error('获取表单类型失败:', error);
        ElMessage.error('获取表单类型失败');
    }
};

// 根据表单类型ID获取表单列表
const getFormOptions = async (typeId: any) => {

    if (!typeId) {
        formOptions.value = [];
        return;
    }
    // typeId = formData.typeId
    console.log(typeId)
    try {
        const res = await getFormList(typeId);
        if (res && res.data && res.data.Result) {
            formOptions.value = res.data.Result;
        }
    } catch (error) {
        console.error('获取表单列表失败:', error);
        ElMessage.error('获取表单列表失败');
    }
};

// 根据表单ID获取表单明细
const getFormDetailList = async (formId: number | null) => {
    if (!formId) {
        formDetails.value = [];
        return;
    }
    console.log(formId)
    try {
        const res = await getfetchFormDetail(formId);
        if (res && res.data && res.data.Result) {
            formDetails.value = res.data.Result;
            // 初始化动态字段
            initDynamicFields(res.data.Result);
        }
    } catch (error) {
        console.error('获取表单明细失败:', error);
        ElMessage.error('获取表单明细失败');
    }
};

// 初始化动态字段
const initDynamicFields = (details: any[]) => {
    formData.dynamicFields = {};
    details.forEach(detail => {
        // 根据控件类型设置默认值
        switch (detail.FieldControl) {
            case 'checkbox':
                formData.dynamicFields[detail.FieldName] = [];
                break;
            case 'date':
            case 'datetime':
                formData.dynamicFields[detail.FieldName] = '';
                break;
            default:
                formData.dynamicFields[detail.FieldName] = detail.FieldDefaultValue || '';
        }
    });
};

// 获取字段选项
const getFieldOptions = (detail: any) => {
    if (detail.FieldProperties) {
        try {
            return JSON.parse(detail.FieldProperties);
        } catch (e) {
            console.error('解析字段属性失败:', e);
            return [];
        }
    }
    return [];
};

// 表单类型变更
const handleTypeChange = (typeId: string | null) => {
    formData.formId = null;
    formDetails.value = [];
    formData.dynamicFields = {};
    getFormOptions(typeId);
};

// 表单变更
const handleFormChange = (formId: number | null) => {
    formDetails.value = [];
    formData.dynamicFields = {};
    getFormDetailList(formId);
};

// 提交表单
const handleSubmit = () => {

    
    console.log('提交的表单数据:', formData);
    ElMessage.success('表单提交成功');
    // 这里可以添加实际的表单提交逻辑
};

// 重置表单
const handleReset = () => {
    formData.dynamicFields = {};
    // 重新初始化动态字段
    initDynamicFields(formDetails.value);
};

// 页面加载时获取表单类型
onMounted(() => {
    getFormTypeOptions();
});

// 监听表单类型变化
watch(() => formData.typeId, (newTypeId) => {
    getFormOptions(newTypeId);
});

// 监听表单变化
watch(() => formData.formId, (newFormId) => {
    getFormDetailList(newFormId);
});
</script>

<style scoped>
.create-container {
    padding: 32px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 32px;
}

.custom-breadcrumb {
    width: 100%;
    max-width: 1400px;
    margin-bottom: 32px;
    margin-top: 0;
    font-size: 15px;
}

.breadcrumb-strong {
    font-weight: bold;
}

.search-card {
    max-width: 1400px;
    width: 100%;
    margin-bottom: 0;
    background: #fff;
    border: 1px solid #e4e7ed;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    border-radius: 10px;
    padding: 18px 18px 8px 18px;
}

.detail-card {
    max-width: 1400px;
    width: 100%;
    background: #fff;
    border: 1px solid #e4e7ed;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    border-radius: 10px;
    padding: 24px 18px 32px 18px;
}

.el-form {
    padding: 0;
}

.el-divider {
    margin-top: 24px;
    margin-bottom: 18px;
    font-size: 18px;
    color: #333;
}

.el-row {
    display: flex;
    flex-wrap: wrap;
    margin-left: -12px;
    margin-right: -12px;
}

.el-col {
    padding-left: 12px;
    padding-right: 12px;
    margin-bottom: 18px;
}

.el-form-item {
    margin-bottom: 0;
    display: flex;
    align-items: center;
}

.el-form-item__label {
    flex: 0 0 90px;
    text-align: right;
    color: #606266;
    font-weight: 500;
    margin-right: 8px;
}

.el-form-item__content {
    flex: 1;
    text-align: left;
}

.el-form-item:last-of-type {
    display: flex;
    justify-content: flex-start;
    gap: 18px;
    margin-left: 102px;
    margin-top: 12px;
}

@media (max-width: 1200px) {

    .search-card,
    .detail-card {
        max-width: 98vw;
        padding: 0 2vw;
    }

    .el-col {
        flex: 0 0 100%;
        max-width: 100%;
    }
}
</style>